# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import subprocess
import sys
import gvn

"""gvn hook runner post-commit svnadmin verify hook
"""

# This will fail until you fix the path to work for your system
SVNADMIN=gvn.SVNADMIN
SENDMAIL='/usr/sbin/sendmail'
# Obviously, you'd want to adjust that too, set to empty string to disable
EMAIL_ADDRESS = 'svn-team'


def RunHook(hi, logger, email=None):
  """Implements gvn.hooks.runner's RunHook interface
  """

  if email is None:
    email = EMAIL_ADDRESS

  args = (SVNADMIN, "verify", '-qr', str(hi.revision), hi.repos_path)
  logger.debug("%s" % ' '.join(args))
  p = subprocess.Popen(args, close_fds=True, stdout=subprocess.PIPE,
                        stderr=subprocess.STDOUT )

  p.wait()
  output = p.stdout.read()

  if output:
    # if configured to mail, do so before returning the error to the sender
    if email:
      mailargs = (SENDMAIL, "-oi", "-f", email, email)
      sendmail = subprocess.Popen(mailargs, stdin=subprocess.PIPE)
      sendmail.stdin.write("""From: %s
To: %s
Subject: svnadmin verify error on repository %s rev %d

Output from %s is:
%s"""% (email, email, hi.repos_path, hi.revision, args, output))

    return output

  return 0
